package com.ifast.album.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ifast.album.domain.AlbumPhoto;
import com.ifast.album.service.AlbumPhotoMsgService;
import com.ifast.album.service.AlbumPhotoService;
import com.ifast.common.annotation.Log;
import com.ifast.common.annotation.OperateRecord;
import com.ifast.common.base.AdminBaseController;
import com.ifast.sys.domain.UserDO;
import com.ifast.sys.filter.token.CsrfTokenCheck;
import com.luculent.util.extension.api.Result;
import com.xiaoleilu.hutool.util.CollectionUtil;

/**
 * 相册管理
 * @author shíQíang㊚
 * @date 2019年4月9日10:05:14
 */
@RequestMapping("/album/photo")
@Controller
public class AlbumPhotoController extends AdminBaseController {
	
    private String preHtml = "lucky/album/photo/";
    @Autowired
    private AlbumPhotoService albumPhotoService;
    @Autowired
    private AlbumPhotoMsgService albumPhotoMsgService;
      
    @Log("进入管理页面")
    @GetMapping()
    @RequiresPermissions("album:photo:photo")
    @CsrfTokenCheck(putValue=true)
    String sysFile(Model model,String albumId){
    	model.addAttribute("albumId", albumId);
        return preHtml+ "list";
    }
    
    @GetMapping("/qyList") 
    @RequiresPermissions("album:photo:qyList")
    String qyList(Model model) {
        return preHtml + "qy_list";
    }
   
    @GetMapping("qyListData") 
    @OperateRecord(OperateName = "列表",ModellName ="相册模块")
    @ResponseBody 
    @Log("列表")
    public Result<Page<AlbumPhoto>> qyListData(Model model,AlbumPhoto explain) {
         Page<AlbumPhoto> page = this.albumPhotoService.selectPage(getPage(AlbumPhoto.class),new EntityWrapper<AlbumPhoto>()
        		.eq("DW_CODE", this.getUser().getDwCode())  
        		.orderBy("create_time",false));
        Optional.ofNullable(page.getRecords()).ifPresent(infos -> infos.parallelStream().forEach(info -> {
        	info.setPhotoMsg(albumPhotoMsgService.selectById(info.getMsgId()).getMsg());
        }));
        
        return Result.ok(page);
    }
    
    @Log("相册列表")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("album:photo:list")
    public Result<Page<AlbumPhoto>> list(String albumId,Integer pageNumber, Integer pageSize, AlbumPhoto fileDTO) {
        // 查询列表数据
        Page<AlbumPhoto> page = getPage(AlbumPhoto.class); 
        page = albumPhotoService.selectPage(page, new EntityWrapper<AlbumPhoto>(fileDTO).orderBy("NIAN",false).orderBy("YUE",false).orderBy("RI",false).orderBy("CREATE_TIME", false).orderBy("PHOTO_ID", false));
        //Optional.ofNullable(page.getRecords()).ifPresent(photos -> photos.stream().forEach(photo -> photo.setPhotoMsg(albumPhotoMsgService.selectById(photo.getMsgId()).getMsg())));
        return Result.ok(page);
    } 
    
    /**
     *  
     * @param model
     * @param id 
     */
    @GetMapping("/add")
    @RequiresPermissions("album:photo:add")
    public String add(Model model, String id){ 
        return  preHtml+"add";
    }
    /**
     * 编辑
     * @param model
     * @param id 
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("album:photo:edit")
    public String edit(Model model,@PathVariable("id") String id){
    	model.addAttribute("info",albumPhotoService.selectById(id));
        return  preHtml+"edit";
    } 
    /**
     * 编辑
     * @param model
     * @param id 
     */
    @GetMapping("/editMsg/{id}")
    @RequiresPermissions("album:photo:editMsg")
    public String editMsg(Model model,@PathVariable("id") String id){
    	model.addAttribute("info",albumPhotoMsgService.selectById(id));
        return  preHtml+"editMsg";
    } 
    /**
     * 查看
     * @param model
     * @param id 
     */
    @GetMapping("/view/{id}")
    @RequiresPermissions("album:photo:edit")
    public String view(Model model,@PathVariable("id") String id){
    	model.addAttribute("info",albumPhotoService.selectById(id));
        return  preHtml+"view";
    }
    
    /**
     * 编辑
     * @param model
     * @param id 
     */
    @PostMapping("/setCover") 
    @ResponseBody
    public Result<?> setCover(Model model,String albumId,String photoId){
    	 return albumPhotoService.cover(albumId, photoId);
     } 
    
    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @Log("删除")
    @RequiresPermissions("album:photo:remove")
    public Result<?> remove(Model model,String id){  
        return  albumPhotoService.remove(id);
    }
    /**
     * 删除
     */
    @PostMapping("/adminRemove")
    @ResponseBody
    @Log("删除")
    @RequiresPermissions("album:photo:adminRemove")
    public Result<?> adminRemove(Model model,String id){  
        return  albumPhotoService.remove(id);
    }
    /**
     * 批量删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("album:photo:batchRemove")
    @Log("批量删除")
    public Result<?> batchRemove(@RequestParam("ids[]") String[] ids) {
    	try {
    		List<String> idList = Arrays.asList(ids);
    		if(CollectionUtil.isNotEmpty(idList)){
        		for(String id : ids){
        			albumPhotoService.remove(id);
        		}
        	}
            return Result.ok();
		} catch (Exception e) {
			log.error(e.toString(),e);
			return Result.fail();
		} 
    }
    /**
     * 保存 
     */
    @PostMapping("/updateMsg")
    @ResponseBody 
    @OperateRecord(OperateName = "保存留言",ModellName ="照片模块留言" )
    public Result<?> updateMsg(HttpServletRequest request,String id,String msg) {
        try{ 
        	UserDO user = this.getUser();
        	Result<?> result = albumPhotoService.editMsg(user.getId().toString(), user.getDwCode(), id, msg);
        	return result;
        }catch (Exception e){
            log.error(e.toString(),e);
            return Result.fail();
        } 
    }
    
    /**
     * 保存 
     */
    @PostMapping("/save")
    @ResponseBody
    @CsrfTokenCheck(checkAjaxValue=true,putAjax=true)
    @OperateRecord(OperateName = "保存照片",ModellName ="相册照片模块" )
    public Result<?> save(HttpServletRequest request,String albumId,String msg,Integer sort) {
        try{ 
        	UserDO user = this.getUser();
        	Result<?> result = albumPhotoService.uploadAdmin(user.getId().toString(), user.getDwCode(), albumId, msg, request);
        	return result;
        }catch (Exception e){
            log.error(e.toString(),e);
            return Result.fail();
        } 
    } 
    
}